package com.hainatong.shiphelper.utils;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Author
 * Github   https://github.com/wildma
 * Date     2018/6/24
 * Desc     ${图片相关工具类}
 */

public class ImageUtils {

    /**
     * 获取Bitmap
     *
     * @param filePath 文件路径
     * @return bitmap
     */
    public static Bitmap getBitmap(final String filePath) {
        if (isSpace(filePath))
            return null;
        return BitmapFactory.decodeFile(filePath);
    }

    private static boolean isSpace(final String s) {
        if (s == null)
            return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取图片路径
     *
     * @param context Context
     * @param uri     图片 Uri
     * @return 图片路径
     */
    public static String getImagePath(Context context, Uri uri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * 获取图片 Uri
     *
     * @param context Context
     * @param path    图片路径
     * @return 图片 Uri
     */
    public static Uri getImageUri(Context context, String path) {
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ", new String[]{path}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (new File(path).exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, path);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }



    public static void addNetImage(Context context, ViewGroup viewGroup , String imgUrl )
    {
        ImageView imageView = new ImageView(context);
        imageView.setScaleType( ImageView.ScaleType.FIT_XY );

        Glide.with(context)
                .load( imgUrl )
                .fitCenter()
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(5)))
                .into( imageView );

        //int hight = DensityUtil.dp2px(context , 70 );
        //int marfin = DensityUtil.dp2px(context , 8);
        int hight = 70 ;
        int marfin =  8;
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams( hight,hight );
        params1.rightMargin = marfin ;
        viewGroup.addView( imageView , params1 );
    }


    public static void addRoundNetImage(Context context, ViewGroup viewGroup , String imgUrl , int RadiusDp)
    {
        ImageView imageView = new ImageView(context);
        imageView.setScaleType( ImageView.ScaleType.FIT_XY );

        Glide.with(context)
                .load( imgUrl )
                .fitCenter()
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(RadiusDp)))
                .into( imageView );

        //int hight = DensityUtil.dp2px(context , 70 );
        //int marfin = DensityUtil.dp2px(context , 8);
        int hight = 70 ;
        int marfin =  8;
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams( hight,hight );
        params1.rightMargin = marfin ;
        viewGroup.addView( imageView , params1 );
    }


    //保存文件到指定路径   DCIM 文件夹
    public static boolean saveImageToGallery(Context context, Bitmap bmp)
    {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_DCIM;
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     *  生成一个保存 图片的 文件名
     * @return
     */
    public static File newImgFileName()
    {
        // 保存图片的位置
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_DCIM;
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";

        File imgfile = new File(appDir, fileName);
        return imgfile;
    }

    //保存文件到指定路径   DCIM 文件夹
    public static boolean saveImageToGallery(Context context, Bitmap bmp,File imgfile)
    {
        // 首先保存图片

        try {
            FileOutputStream fos = new FileOutputStream(imgfile);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(imgfile);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }



}
